<template>
    <div>
        <div class="gzdsx-pos-autocomplete" v-click-outside="hide">
            <input
                    type="text"
                    class="input"
                    placeholder="Search for a customer..."
                    @input="handleInput"
            >
            <div class="suggestions" v-if="suggestionVisible">
                <div class="suggestion-con" v-if="loading">
                    <i class="gzdsx-pos-spinner"></i>
                </div>
                <div class="suggestion-con" v-if="suggestions===0&&!loading">No results found.</div>
                <div class="suggestion-item" v-for="(item,index) in suggestions" :key="index" @click="select(item)">
                    <div>
                        <img :src="item.avatar_url" class="suggestion-item__image" alt="">
                    </div>
                    <div class="suggestion-item__name">
                        <div>{{ item.username }}({{ item.email }})</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="gzdsx-pos-autocomplete-tips">Please enter 2 or more characters</div>
    </div>
</template>

<script>
let controller = new AbortController();
export default {
    name: "SearchCustomer",
    props: {},
    data() {
        return {
            suggestions: [],
            suggestionVisible: false,
            loading: false
        }
    },
    methods: {
        handleInput(event) {
            const search = event.target.value;
            if (search.length < 2) {
                return;
            }

            if (controller) {
                controller.abort();
                controller = new AbortController();
            }

            this.loading = true;
            this.suggestionVisible = true;
            this.$http.get('/customers', {params: {search, per_page: 50}}).then(response => {
                this.suggestions = response;
            }).catch(() => {

            }).finally(() => {
                this.loading = false;
            });
        },
        imageSrc(src) {
            return src.replace('http://noodlebox.test.com', 'https://noodlebox.ie');
        },
        select(item) {
            this.$emit('select', item);
            this.suggestionVisible = false;
        },
        hide() {
            this.suggestionVisible = false;
        }
    },
    mounted() {
        // var that = this;
        // this.$el.addEventListener('click', function (event) {
        //     event.stopPropagation();
        // });
        // document.body.addEventListener('click', function () {
        //     that.suggestionVisible = false;
        // })
    }
}
</script>

<style scoped>

</style>